import {
	INodeExecutionData,
	type IExecuteFunctions,
	type INodeType,
	type INodeTypeDescription,
} from 'n8n-workflow';
import axios from 'axios';
import { createCacheTask } from './util';
import { v1 } from 'uuid';

export class TaskNode implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'UNC任务执行',
		name: 'uncTaskCreate',
		icon: 'file:webhook.svg',
		group: ['transform'],
		version: 1,
		description: 'UNC任务执行',
		defaults: {
			name: 'UNC Task Create',
		},
		inputs: ['main'],
		outputs: ['main'],
		credentials: [
			{
				name: 'TaskNodeApi',
				required: true,
				displayName: '任务执行凭证',
			},
		],
		properties: [
			{
				displayName: '任务ID',
				name: 'parent_task_id',
				type: 'string',
				default: '',
				placeholder: '请输入任务ID',
				required: true,
			},
			{
				displayName: '任务队列',
				name: 'task_queue',
				type: 'string',
				default: '',
				placeholder: '请输入任务队列',
				required: true,
			},
			{
				displayName: '任务参数',
				name: 'task_params',
				type: 'string',
				default: '',
				placeholder: '请输入任务参数',
				required: true,
			},
			{
				displayName: '超时时间',
				name: 'task_timeout',
				type: 'number',
				default: 60,
				placeholder: '请输入任务超时时间(单位:秒)',
				required: true,
			},
		],
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items: any = [];
		let itemIndex = 0;
		try {
			const parent_task_id = this.getNodeParameter('parent_task_id', 0) + '';
			const task_queue = this.getNodeParameter('task_queue', 0) + '';
			const task_params = this.getNodeParameter('task_params', 0) + '';
			const task_timeout = Math.max(parseInt(this.getNodeParameter('task_timeout', 0) + ''), 0);
			const credentials = await this.getCredentials('TaskNodeApi');
			const address = credentials?.address + '';
			const task_id = v1();
			// 调用外部接口创建任务
			const data = {
				"task_req": {
					"user_id": "unc",
					"task_type": "audit_task",
					"task_subtype": task_queue,
					"context": {
					},
					"param": {
						"start_phase": "NEW",
						"origin": "2",
						"arguments": {
							"username": "unc",
							"pid": parent_task_id,
							"args": task_params
						}
					}
				},
				task_id
			}
			await axios.post(address, data);
			// 创建缓存任务
			const ret = await createCacheTask({ task_id, task_timeout });
			// 返回任务执行结果
			items.push(...this.helpers.returnJsonArray({ ...ret }));
		} catch (error) {
			// 异常错误处理
			if (this.continueOnFail()) {
				items.push({ json: {}, error, pairedItem: itemIndex });
			} else {
				if (error.context) {
					error.context.itemIndex = itemIndex;
				}
				throw error;
			}
		}
		return [items];
	}

}
